<template>
  <el-link v-if="schema.type === 'link'" :disabled="confirmLoading" v-bind="attrs" @click="click">
    <Body :body="schema.body" />
  </el-link>
  <el-button
    v-else-if="schema.type === 'button'"
    v-bind="attrs"
    @click="click"
    :disabled="confirmLoading"
    :loading="confirmLoading"
  >
    <Body :body="schema.body" />
  </el-button>
</template>

<script setup>
import { ElMessageBox } from 'element-plus'
import { ref, unref, getCurrentInstance, inject, watchEffect } from 'vue'
import Body from '../../container/body/index.vue'
import { handleApi } from '../../common/api'
import { filterAttrByExclude, replaceValue, downFileByUrl, findVarByName } from '../../common/util'
import { LOWCODE_RECORD_DATA } from '../../common/constant'
import { useRouter } from 'vue-router'
import { deepCopy } from '@/utils/index'
import { DialogService } from '@/core/hook/dialog-service'

defineOptions({ name: 'ActionCom' })

const instance = getCurrentInstance()
const props = defineProps({
  schema: {
    type: Object,
    required: true
  }
})

const confirmLoading = ref(false)

const lowCodeCrud = inject('lowCodeCrud')
const lowCodeDialog = inject('lowCodeDialog')
const lowCodeDrawer = inject('lowCodeDrawer')
const lowCodeForm = inject('lowCodeForm')

const router = useRouter()

const schema = props.schema
const api = schema.api
const messageContent = replaceValue(schema.messageContent || '', instance)
const messageTitle = schema.messageTitle || '温馨提示'
const attrs = ref()
const actionType = schema.actionType

watchEffect(() => {
  attrs.value = {
    ...filterAttrByExclude(
      [
        'actionType',
        'refreshTable',
        'link',
        'validate',
        'messageContent',
        'downloadFilePath',
        'downloadFileName',
        'prePositionHook',
        'validateResolve'
      ],
      props.schema,
      {
        level: 'type'
      }
    )
  }
})

function click() {
  if (schema.prePositionHook) {
    const rs = findVarByName(instance, LOWCODE_RECORD_DATA)
    schema.prePositionHook(rs?.data)
  }
  if (actionType === 'dialog') {
    if (schema.dialog) {
      DialogService(schema.dialog)
    }
  } else if (actionType === 'link') {
    const link = schema.link
    router.push(replaceValue(link, instance))
  } else if (actionType === 'delete') {
    ElMessageBox.confirm(messageContent, messageTitle, {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      if (!api) {
        return
      }
      handleApi(api, instance).then(() => {
        if (schema.refreshTable) {
          if (lowCodeCrud) {
            lowCodeCrud.refreshTable()
          }
        }
      })
    })
  } else if (actionType === 'submit') {
    if (!lowCodeForm.formRef.value) {
      return
    }
    let value = lowCodeForm.model.value
    if (schema.validate && typeof schema.validate === 'function') {
      value = schema.validate(lowCodeForm.model.value)
      if (!value) {
        return
      }
    }
    unref(lowCodeForm.formRef).validate((valid) => {
      if (valid) {
        if (!lowCodeForm?.schema?.api) {
          return
        }
        confirmLoading.value = true
        handleApi(lowCodeForm.schema.api, instance, value)
          .then(() => {
            if (lowCodeForm) {
              unref(lowCodeForm.formRef).resetFields()
            }
            if (lowCodeDialog) {
              lowCodeDialog.hide()
            }
            if (lowCodeDrawer) {
              lowCodeDrawer.hide()
            }
            if (schema.refreshTable) {
              if (lowCodeCrud) {
                lowCodeCrud.refreshTable()
              }
            }
          })
          .finally(() => {
            confirmLoading.value = false
          })
      }
    })
  } else if (actionType === 'cancel') {
    if (lowCodeForm) {
      lowCodeForm.resetFields()
    }
    if (lowCodeDialog) {
      lowCodeDialog.hide()
    }
    if (lowCodeDrawer) {
      lowCodeDrawer.hide()
    }
  } else if (actionType === 'back') {
    router.back()
  } else if (actionType === 'confirm') {
    ElMessageBox.confirm(messageContent, messageTitle, {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      if (!api) {
        return
      }
      handleApi(api, instance).then(() => {
        if (schema.refreshTable) {
          if (lowCodeCrud) {
            lowCodeCrud.refreshTable()
          }
        }
      })
    })
  } else if (actionType === 'download') {
    const downloadFilePath = schema.downloadFilePath
    const downloadFileName = schema.downloadFileName
    const filePath = replaceValue(downloadFilePath, instance)
    const fileName = replaceValue(downloadFileName, instance)
    downFileByUrl(filePath, fileName)
  } else if (actionType === 'ajax') {
    const api = schema.api
    if (!api) {
      return
    }
    confirmLoading.value = true
    handleApi(api, instance)
      .then(() => {})
      .finally(() => {
        setTimeout(() => {
          confirmLoading.value = false
        }, 300)
      })
  } else if (actionType === 'validate') {
    console.log('lowCodeForm', lowCodeForm);
    if (lowCodeForm) {
      lowCodeForm.formRef.validate((valid) => {
        if (valid) {
          if (schema.validateResolve) {
            schema.validateResolve(deepCopy(lowCodeForm.model))
          }
          if (lowCodeDialog) {
            lowCodeDialog.hide()
          }
          if (lowCodeDrawer) {
            lowCodeDrawer.hide()
          }
        }
      })
    }
  }
}
</script>
